package com.agentlab.imitation.web.action;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.velocity.app.VelocityEngine;
import org.hibernate.mapping.Map;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
import org.springframework.ui.velocity.VelocityEngineUtils;

import com.agentlab.imitation.bean.PageView;
import com.agentlab.imitation.bean.User;
import com.agentlab.imitation.common.CommonConstant;
import com.agentlab.imitation.mail.EmailSender;
import com.agentlab.imitation.service.UserService;
import com.agentlab.imitation.util.DateTimeUtils;
import com.agentlab.imitation.util.MD5;
import com.agentlab.imitation.util.ToString;
import com.agentlab.imitation.util.WebUtil;
import com.opensymphony.xwork2.ActionSupport;


@Controller 
public class UserRegAction extends ActionSupport {

	@Resource UserService usersService;
	@Resource JavaMailSenderImpl mailSender;
	@Resource VelocityEngine  velocityEngine;
	private User user;
	
	private String message; // ajax result

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	/**
	 * 用户管理列表显示
	 */
	public String listUI(){
		HttpServletRequest req = ServletActionContext.getRequest();
		//最大页 10，当前页 1
		int iPage = 1;
		if(req.getParameter("page") != null){
			String spage = req.getParameter("page").toString();
			iPage = (Integer.parseInt(spage))<1 ?1 : Integer.parseInt(spage);
		}
		PageView<User> pageView = new PageView<User>(10, iPage);
		LinkedHashMap<String, String> orderby = new LinkedHashMap<String, String>();
		orderby.put("createtime", "desc");

		StringBuffer jpql = new StringBuffer("");
		List<Object> params = new ArrayList<Object>();
		pageView.setQueryResult(
				usersService.getScrollData(pageView.getFirstResult(), pageView.getMaxresult()
						, jpql.toString(), params.toArray(), orderby)
		);
		req.setAttribute("pageView", pageView);
		return "userlist";
	}
	
//	/**
//	 * 启用
//	 * @throws IOException 
//	 */
//	public String enable() throws IOException{
//		HttpServletRequest req = ServletActionContext.getRequest();
//		String[] useremail = null;
//		useremail = (String[]) req.getParameterMap().get("useremails");
//		usersService.enable((Serializable[])useremail);
//		req.setAttribute("message", "启用成功");
//		return "listaction";
//	}
	/**
	 * 禁用
	 * @throws IOException 
	 */
	public String delete() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		String[] useremail = null;
		useremail = (String[]) req.getParameterMap().get("useremails");
		usersService.delete((Serializable[])useremail);
		req.setAttribute("message", "禁用成功");
		return "listaction";
	}
	
	/**
	 * 检查用户名是否存在
	 */
	public String checkUserByName() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String username = request.getParameter("user.username");
		if (usersService.getUserByName(username) != null) {
			this.setMessage("存在");
		} else {
			this.setMessage("不存在");
		}
		return "message";
	}
	
	/**
	 * 检查邮箱是否已经注册过
	 */
	public String checkUserByEmail() {
		HttpServletRequest request = ServletActionContext.getRequest();
		String email = request.getParameter("user.email");
		if (usersService.getUserByEmail(email) != null) {
			this.setMessage("存在");
		} else {
			this.setMessage("不存在");
		}
		return "message";
	}
	
	public String addUI(){
		HttpServletRequest req = ServletActionContext.getRequest();
		setUser(new User());
		return "addui";
	}
	/**
	 * 发送注册激活邮件
	 */
	private boolean sendRegEmail(final User user) {  
        MimeMessagePreparator preparator = new MimeMessagePreparator() {  
            public void prepare(MimeMessage mimeMessage) throws Exception {  
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"UTF-8");  
                message.setSubject("激活-重庆模拟志愿填报系统");  
                message.setTo(user.getEmail());  
                message.setFrom("agent1103@swu.edu.cn");  
                java.util.Map model = new HashMap();  
                 model.put("user", user);  
                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "registration-confirmation.vm","UTF-8", model);  
                message.setText(text, true);  
            }  
        };  
        try{  
            this.mailSender.send(preparator);  
            return true;  
        }catch(MailException e) {  
            e.printStackTrace();  
            return false;  
        }  
	}  
	
	/**
	 * 重新发送注册激活邮件
	 */
	public String sendRegEmailAgain() {  
		HttpServletRequest req = ServletActionContext.getRequest();
		String userId = req.getParameter("userId").trim();
		if(userId != null && !userId.equals("null")){
			User user = usersService.find(Integer.parseInt(userId));
			if(user ==null) //用户不存在
			{
				req.setAttribute("regresult", "参数错误！用户不存在！");
				
			}else{
				if(this.sendRegEmail(user)){
					req.setAttribute("regresult", "激活邮件已发出，请通过邮件激活帐号");
				}else
				{
					req.setAttribute("regresult", "激活邮件发送失败");
				}
			}
		}else{  //参数 不正确
			req.setAttribute("regresult", "参数错误！激活邮件发送失败！");
		}
		req.setAttribute("userId", userId);
		return "register_result";
	}
	
	/**
	 * 发送找回密码邮件
	 */
	private boolean sendPasswordEmail(final User user) {  
        MimeMessagePreparator preparator = new MimeMessagePreparator() {  
            public void prepare(MimeMessage mimeMessage) throws Exception {  
                MimeMessageHelper message = new MimeMessageHelper(mimeMessage,true,"UTF-8");  
                message.setSubject("找回密码-重庆模拟志愿填报系统");  
                message.setTo(user.getEmail());  
                message.setFrom("agent1103@swu.edu.cn");  
                java.util.Map model = new HashMap();  
                 model.put("username", user.getUsername());  
                 model.put("password",user.getPassword());  
                String text = VelocityEngineUtils.mergeTemplateIntoString(velocityEngine, "findpassword.vm","UTF-8", model);  
                message.setText(text, true);  
            }  
        };  
        try{  
            this.mailSender.send(preparator);  
            return true;  
        }catch(MailException e) {  
            e.printStackTrace();  
            return false;  
        }  
	}  
	
	public String findPassUI(){
		return "findpassword";
	}
	
	/**
	 * 找回密码
	 */
	public String findPassword() {  
		HttpServletRequest req = ServletActionContext.getRequest();
		String type = req.getParameter("findPasswordType");
		String keyword = req.getParameter("keyword");
		User user = null;
		if(type != null && !"".equals(type) && keyword!=null && !"".equals(keyword)){
			if(type.equals("1")){ //用户名
				user = usersService.getUserByName(keyword);
			}else{  //email
				user = usersService.getUserByEmail(keyword);
			}
			if(user != null){
				user.setPassword(MD5.genRandomNum(8));//生成一个随机密码
				this.sendPasswordEmail(user);
				user.setPassword(MD5.MD5Encode(user.getPassword()));
				usersService.update(user);//更新密码
				req.setAttribute("findpassword_result", "邮件已发送，请查看邮箱！");
			}else{
				req.setAttribute("findpassword_result", "用户不存在！");
			}
			
		}else{  //参数 不正确
			req.setAttribute("findpassword_result", "参数错误！");
		}
		return "findpassword_result";
	}
	
	
	/**
	 * 注册
	 */
	public String register(){
		HttpServletRequest req = ServletActionContext.getRequest();
		try {
			User orgusers = getUser(); //
			orgusers.setUsername(user.getUsername());
			orgusers.setEmail(user.getEmail());
			String newpass = req.getParameter("newuserpass");
			if(StringUtils.isNotBlank(newpass)){
				orgusers.setPassword(MD5.MD5Encode(newpass));
			}else{
				orgusers.setPassword(MD5.MD5Encode(user.getPassword()));
			}
			orgusers.setStatus(Short.parseShort("0"));//0表示没有激活，打算通过邮件激活
			orgusers.setCreateTimestamp(DateTimeUtils.getDateTimeStamp());
			orgusers.setLastlogintime(DateTimeUtils.getDateTimeStamp());
			orgusers.setLastloginip(WebUtil.getIpAddr(req));
			usersService.save(user);
			System.out.println("[register()]user:" + new ToString(user).toString());
			//邮件发送方法1  ,测试成功
			/*
			String mailTitle = "用户注册-重庆志愿模拟填报系统";
			String mailContent = "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"GBK\"><head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/> </head>  <body>  <h5>  尊敬的会员：  </h5> <h5> "    
				+"   您的激活码已审核通过，于系统时间${user.lastlogintime}生成邀请。  "
				+"</h5>    <h5>     您的激活码：${user.userid}，请您通过下面的链接，完成您的帐户注册激活：  </h5>  "  
				+"   <a href=\"http://172.18.16.171:8080/imitation/logon/userreg_active.action?userId=" + user.getUserid() +"\">http://172.18.16.171:8080/imitation/logon/userreg_active.action?userId="+ user.getUserid() +"</a>  "
				+"<h5> 系统将自动跟踪并激活您的帐户。</h5>   <h5>      感谢您的关注和支持！  </h5>   "    
				+"--------------------------------------------------------------------  <h5>     请勿直接回复本邮件，如有任何疑问，联系网站客服人员   </h5>  </body>  </html>  ";
			System.out.println("mailContent:"+mailContent);
			EmailSender.send(new String[]{user.getEmail()},mailTitle, mailContent, null , "text/html");
			*/
			//发送邮件方法2
			sendRegEmail(user);
			req.setAttribute("regresult", "激活邮件已发出，请通过邮件激活帐号");
			req.setAttribute("userId", user.getUserid());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "register_result";
	}
	
	/**
	 * 激活
	 */
	public String active(){
		HttpServletRequest req = ServletActionContext.getRequest();
		try {
			String userId = req.getParameter("userId").trim();
			if(userId == null || userId.equals("")){
				req.setAttribute("activeresult", "要激活的用户不存在！");
				return "activeresult";
			}else
			{
				User user = usersService.find(Integer.parseInt(userId));
				if(user == null)
				{
					req.setAttribute("activeresult", "要激活的用户不存在！");
					return "activeresult";
				}else
				{
					if(user.getStatus() == 1) //用户已经激活
					{
						req.setAttribute("activeresult", "用户已激活过！");
						return "activeresult";
					}
					user.setStatus(Short.parseShort("1"));
					usersService.update(user);
					req.setAttribute("activeresult", "用户激活成功，请登录！");
					return "activeresult";
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "activeresult";
	}
	
	/**
	 * 增加或修改
	 */
	public String addorupdate(){
		HttpServletRequest req = ServletActionContext.getRequest();
		try {
			User orgusers = getUser();
			if(orgusers == null){
				orgusers = new User();
			}
			orgusers.setUsername(user.getUsername());
			orgusers.setEmail(user.getEmail());
			String newpass = req.getParameter("newuserpass");
//			String[] rols = null;
//			rols = (String[])  req.getParameterMap().get("userrolecode");
			
			if(StringUtils.isNotBlank(newpass)){
				orgusers.setPassword(MD5.MD5Encode(newpass));
			}else{
				orgusers.setPassword(MD5.MD5Encode(user.getPassword()));
			}
			orgusers.setStatus(Short.parseShort("1"));
			if(user.getUserid() != null){
				if(newpass.length()==0){
					orgusers.setPassword(user.getPassword());
				}
				usersService.update(user);
			}else{
				orgusers.setCreateTimestamp(DateTimeUtils.getDateTimeStamp());
				usersService.save(user);
			}
			
			
			req.getSession().setAttribute("addupdateresultmsg", "增加用户成功！用户名：" + orgusers.getUsername());
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "listaction";
	}
	
	/**
	 * 编辑
	 * @throws IOException 
	 */
	
	public String editUI() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		String eitcode = req.getParameter("editcode");
		if(eitcode!= null){
			int cid = Integer.parseInt(eitcode.trim());
			User tempuser = usersService.find(cid);
			if(tempuser != null){
				setUser(tempuser);
			}else{
				req.setAttribute("message", "编号不存在");
				return "listaction";
			}
		}
		return "addui";
	}
	/**
	 * 编辑
	 * @throws IOException 
	 */
	public String edit() throws IOException{
		HttpServletRequest req = ServletActionContext.getRequest();
		User user = new User();
		String[] rols = null;
		rols = (String[])  req.getParameterMap().get("userrolecode");
		if(rols != null && req.getParameter("userEmail") != null  && rols.length > 0){
			user.setEmail(req.getParameter("userEmail").trim());
			String userpass = MD5.MD5Encode(req.getParameter("userPass"));
			if(userpass != null){
				user.setPassword(userpass);
			}
			String captcha = req.getParameter("newaccountcaptcha").toUpperCase().trim();
			if(!captcha.equals(req.getSession().getAttribute("random").toString().toUpperCase())){
				req.setAttribute("message", "验证码输入错误");
				return "success";
			}
			user.setCreateTimestamp(DateTimeUtils.getDateTimeStamp());
			user.setStatus(Short.parseShort("1"));
			usersService.update(user);
			return "listaction";
		}
		return "success";
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}
}
